/*!
 * Copyright (c)2008-2009, stauren.net All rights reserved.
 * @file calendar.js
 * @class __.widget.Calendar
 * @author <a href="mailto:stauren@stauren.net">stauren</a>
 * @revision:
 */

__.set("__.widget");
__.log('Calendar: Class begin.');
(function() {
  var  _CFG = {
    I18N : {
      weekdays_short : ['日','一','二','三','四','五','六'],
      weekdays_medium : ['周日','周一','周二','周三','周四','周五','周六'],
      weekdays_long : ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'],
      months_short : ['一','二','三','四','五','六','七','八','九','十','十一','十二'],
      months_long : ['一月','二月','三月','四月','五月','六月','七月','八月','九','十月','十一月','十二月'],
      needSelect : '请先选择日期'
    }
    ,
    DOM : {
      hourClass : 'du-cal-hour',
      minuteClass : 'du-cal-minute',
      secondClass : 'du-cal-second'
    }
    ,
    defInstCfg : {
      showAfterInit :false,
      level : 6,
      modal : false,
      followMouse : true
    }
    ,
    sLogPrefix : 'duCalendar: '
  },

  _ = __._
  ,

  /**#@+
   * the private functions
   * @private
   * @memberOf __.widget.Calendar
   */
  
  /**
   * initiate elements id and name
   */
  _initI18n = function() {
    var dc = YAHOO.widget.Calendar._DEFAULT_CONFIG, ci = _CFG.I18N;
    dc.WEEKDAYS_SHORT.value = ci.weekdays_short;
    dc.WEEKDAYS_MEDIUM.value = ci.weekdays_medium;
    dc.WEEKDAYS_LONG.value = ci.weekdays_long;
    dc.MONTHS_SHORT.value = ci.months_short;
    dc.MONTHS_LONG.value = ci.months_long;
  },

  /**
   * the method used to set the onLoad handler of uploading,
   * @private
   * @param {object} that the calendar instance 
   */
  _initYuiCalender = function(that) {
    var dt = new Date(), ctn;
    that._oPopup = new __.widget.Popup('', {
      onOk : function() {
        var ct = that.oContainer.parentNode, cd = _CFG.DOM;
        if (that.dateValue) {
          var temp = _.f('.'+ cd.hourClass, ct);
          that.timeValue = temp && temp.value ? temp.value : '';
          temp = _.f('.'+ cd.minuteClass, ct)
          that.timeValue += temp && temp.value ? ':'+ temp.value : '';
          temp = _.f('.'+ cd.secondClass, ct)
          that.timeValue += temp && temp.value ? ':'+ temp.value : '';
          if (that._config.couplingIpt) {
            _.f(that._config.couplingIpt).value = that.dateValue +' '+ that.timeValue;
          }
        } else {
          alert(_CFG.I18N.needSelect);
        }
      },
      bShowAfterInit : that._config.showAfterInit,
      bModal : that._config.modal,
      bCenter : !that._config.followMouse
    });
    ctn = that._oPopup.body;
    _.addClass(ctn.parentNode, 'yui-skin-sam');
    that.oContainer = ctn;
    that.oYuiCal = new YAHOO.widget.Calendar(ctn);
    that.oYuiCal.select([dt.getMonth()+1, dt.getDate(), dt.getFullYear()].join('/'));
    that.dateValue = [dt.getFullYear(), dt.getMonth()+1, dt.getDate()].join('-');
    _addEvent(that);
    if (that._config.showAfterInit) {
      that.oYuiCal.render();
    }
    that._oPopup.setSize();
  }
  ,

  /**
   * add events listener
   * @private
   * @param {object} that the calendar instance
   */
  _addEvent = function(that) {
    var ipt;
    if (that._config.couplingIpt) {
      ipt = _.f(that._config.couplingIpt);
      if (ipt) {
        _.on(that._config.couplingIpt, 'click', function(e) {
          var pos;
          if (that._config.followMouse) {
            pos = [e.clientX, e.clientY];
          }
          that.show(pos);
        });
        that.oYuiCal.selectEvent.subscribe(function(t, args, o) {
          var dt = args[0][0];
          that.dateValue = dt.join('-');
          //that.hide();
        });
      }
    }
  }
  ,

  /**
   * create elements for time input
   * @private
   * @param {object} that the calendar instance
   */
  _createTimeEls = function(that) {
    var hours = [], minutes = [], seconds = [],
     level = that._config.level, dt = new Date(), timecontainer,
     h = dt.getHours(), m = dt.getMinutes(), s = dt.getSeconds(), obj;

    obj = {
      css : 'padding:5px 0 0 0;position:relative;left:0;top:-35px;float:left;',
      child : []
    };
    if (level > 3) {
      _.e(_.range(24), function(o) {
        var sel = o == h ? 'selected' : false;
        o = o < 10 ? '0'+ o : o;
        hours[hours.length] = {
          tag : 'option', value : o, text : o, attrs : { selected : sel }
        };
      });
      obj.child.push({
        tag : 'select', css : 'margin:0 5px 0 4px;', child : hours, cls : _CFG.DOM.hourClass
      });
    }
    if (level > 4) {
       _.e(_.range(60), function(o) {
        var sel = o == m ? 'selected' : false;
        o = o < 10 ? '0'+ o : o;
        minutes[minutes.length] = {
          tag : 'option', value : o, text : o, attrs : { selected : sel }
        };
      });
      obj.child.push({
        tag : 'span', text : ':'
      });
      obj.child.push({
        tag : 'select', css : 'margin:0 5px;', child : minutes, cls : _CFG.DOM.minuteClass
      });
    }
    if (level > 5) {
      _.e(_.range(60), function(o) {
        var sel = o == s ? 'selected' : false;
        o = o < 10 ? '0'+ o : o;
        seconds[seconds.length] = {
          tag : 'option', value : o, text : o, attrs : { selected : sel }
        };
      });
      obj.child.push({
        tag : 'span', text : ':'
      });
      obj.child.push({
        tag : 'select', css : 'margin-left:5px;', child : seconds, cls : _CFG.DOM.secondClass
      });
    }
    timecontainer = _.addEl(obj);
    _.insertAfter(timecontainer, that.oContainer);
  }
  ;

  /**#@-*/

  __.widget.Calendar = __.Class.extend(
  /**
   * @lends __.widget.Calendar.prototype
   */
  {

    /**
     * configuration data object
     * @private
     * @type object
     */
    _config : {},

    /**
     * popup window
     * @private
     * @type object
     */
    _oPopup : null,

    /**
     * calender initated indicator
     * @type object
     */
    initiated : false,

    /**
     * yui calendar object
     * @type object
     */
    oYuiCal : null,

    /**
     * date value, Y-M-d
     * @type string
     */
    dateValue : '',

    /**
     * time value, H:m:s
     * @type string 
     */
    timeValue : '',

    /**
     * container
     * @type object
     */
    oContainer : null,

    /**
     * the constructor of image uploader
     * @constructs
     * @param {object} config detail config object
     * @config {string} couplingIpt id of the coupling input
     * @config {boolean} showAfterInit show calender immediately
     * @config {integer} level date and time level, max 6 (y m d H M s), min 3
     * @config {boolean} modal decide this dialog's mode
     * @config {boolean} followMouse popout dialog at mouse position
     */
    init : function(config) {
      var that = this;
      config = config || {};
      this._config = _.clone(_CFG.defInstCfg);
      _.objExtend(that._config, config);
      __.load(['popup http://localhost/att/workspace/os/svn/trunk/lib/calendar/calendar-min.js',
        'http://localhost/att/workspace/os/svn/trunk/lib/calendar/assets/calendar.css']
        , function() {

        _initI18n();
        _initYuiCalender(that);
      });
    }
    ,

    /**
     * render the canlender elements
     */
    render : function() {
      var that = this;
      that.oYuiCal.render();
      that.initiated = true;
      if (that._config.level > 3) {
        _createTimeEls(that);
      }
    }
    ,

    /**
     * show the calendar
     * @param {array} position x,y of popout position
     */
    show : function(pos) {
      var that = this, iid = false, fn = function() {
        if (that.oYuiCal) {
          iid !== false && clearInterval(iid);
          if (!that.initiated) {
            that._oPopup.show(pos);
            that.render();
            that._oPopup.setSize();
          } else {
            that._oPopup.show(pos);
          }
        }
      };
      if (this.oYuiCal) {
        fn();
      } else {
        iid = setInterval(fn, 100);
      }
    }
    ,

    /**
     * hiden the calendar
     */
    hide : function() {
      if (this._oPopup) {
        this._oPopup.hide();
      } else {
        this.oYuiCal.hide();
      }
    }
  });

  _.addStyle('\
.yui-skin-sam div.yui-calcontainer {\
border:0;\
background:transparent;\
margin-top:10px;\
height:220px;\
width:172px;\
}\
');
  __.widget.Calendar.I18N = _CFG.I18N;
})();
__.log('Calendar: Class end.');
